package zelix.hack.hacks;

import zelix.hack.Hack;
import zelix.hack.HackCategory;
import net.minecraft.block.state.IBlockState;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EnumCreatureAttribute;
import net.minecraft.init.Enchantments;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.item.ItemTool;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent.LeftClickBlock;
import zelix.utils.Utils;
import zelix.utils.Wrapper;

public class AutoTool extends Hack {
	public AutoTool() {
		super("AutoTool", HackCategory.PLAYER);

	}

	@Override
	public String getDescription() {
		return "Automatically switch to the best tools when mining or attacking";
	}

	@Override
	public void onLeftClickBlock(LeftClickBlock event) {
		Utils.nullCheck();
		equipBestTool(Wrapper.INSTANCE.world().getBlockState(event.getPos()));

	}

	@Override
	public void onAttackEntity(AttackEntityEvent event) {
		Utils.nullCheck();
		equipBestWeapon();

	}

	private void equipBestTool(IBlockState blockState) {
		int bestSlot = -1;
		double max = 0;
		for (int i = 0; i < 9; i++) {
			ItemStack stack = Wrapper.INSTANCE.player().inventory.getStackInSlot(i);
			if (stack.isEmpty())
				continue;
			float speed = stack.getDestroySpeed(blockState);
			int eff;
			if (speed > 1) {
				speed += ((eff = EnchantmentHelper.getEnchantmentLevel(Enchantments.EFFICIENCY, stack)) > 0
						? (Math.pow(eff, 2) + 1)
						: 0);
				if (speed > max) {
					max = speed;
					bestSlot = i;
				}
			}
		}
		if (bestSlot != -1)
			equip(bestSlot);
	}

	public static void equipBestWeapon() {
		int bestSlot = -1;
		double maxDamage = 0;
		for (int i = 0; i < 9; i++) {
			ItemStack stack = Wrapper.INSTANCE.player().inventory.getStackInSlot(i);
			if (stack.isEmpty())
				continue;
			if (stack.getItem() instanceof ItemTool) {
				double damage = (((ItemTool) stack.getItem()).getDamage(stack)
						+ (double) EnchantmentHelper.getModifierForCreature(stack, EnumCreatureAttribute.UNDEFINED));
				if (damage > maxDamage) {
					maxDamage = damage;
					bestSlot = i;
				}
			} else if (stack.getItem() instanceof ItemSword) {
				double damage = (((ItemSword) stack.getItem()).getAttackDamage()
						+ (double) EnchantmentHelper.getModifierForCreature(stack, EnumCreatureAttribute.UNDEFINED));
				if (damage > maxDamage) {
					maxDamage = damage;
					bestSlot = i;
				}
			}
		}
		if (bestSlot != -1)
			equip(bestSlot);
	}

	private static void equip(int slot) {
		Wrapper.INSTANCE.player().inventory.currentItem = slot;
		// Wrapper.INSTANCE.controller().syncCurrentPlayItem();

	}

}
